﻿using ScreenMonitor.Common;
using ScreenMonitor.Common.Objects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace ScreenMonitor.ServerLib
{
    /// <summary>
    /// 为签到命令提供方法
    /// </summary>
    public static class SignCommand
    {
        private static List<ClientObject> SignList;
        private static int WaitRate;
        private static int WaitedTime = 0;
        private static bool IsCancelWait = false;
        private static Task WaitTask;

        /// <summary>
        /// 发送签到命令给远端
        /// </summary>
        /// <param name="Clients">要接收命令的远端</param>
        /// <param name="IsLockScreen">是否独占屏幕操作</param>
        /// <param name="SignLimitTime">签到限制时间</param>
        public static void Send(List<ClientObject> Clients, bool IsLockScreen, int SignLimitTime)
        {
            SignList = Clients;
            List<TcpClient> clist = new List<TcpClient>(); ;
            foreach (ClientObject obj in Clients)
            {
                obj.SignState = SignState.Signing;
                clist.Add((TcpClient)obj.Client);
            }
            SignRequestObject Reobj = new SignRequestObject();
            Reobj.IsLockScreen = IsLockScreen;
            Reobj.SignLimitTime = SignLimitTime;
            WaitRate = SignLimitTime + 3;
            CommandObjects.TcpCommandCenter.SendCommandToAllWithData(clist, CommandType.NeedToSign, Reobj.ToByte());
            if (WaitTask != null && WaitTask.Status == TaskStatus.Running)
            {
                IsCancelWait = true;
                while (IsCancelWait == true)
                {
                    System.Threading.Thread.Sleep(1000);
                }
            }
            WaitTask = new Task(WaitForResult);
            WaitTask.Start();
        }

        private static void WaitForResult()
        {

            while (!IsCancelWait && WaitRate > WaitedTime)
            {
                System.Threading.Thread.Sleep(1000);
                WaitedTime += 1;
            }
            WaitedTime = 0;
            if (IsCancelWait == true)
            {
                IsCancelWait = false;
                return;
            }
            foreach (ClientObject obj in SignList)
            {
                if (obj.SignState == SignState.Signing)
                    obj.SignState = SignState.UnSigned;
            }
        }

    }
}
